package com.pz.minioproxy.controller;

import com.pz.gulimall.common.utils.R;
import com.pz.minioproxy.service.BigFileDownloadService;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class DownloadBigFileController {
    @Resource
    private BigFileDownloadService bigFileDownloadService;

    /**
     * 获取大文件各个分块的minio下载连接
     * @param md5 大文件md5
     * @return 大文件所有分块的下载连接,以及文件名
     */
    @GetMapping("/upload-bigfile/get-blobLinks")
    public R getBigfileBlobsObjName(@RequestParam("md5") String md5){
        List<String> links = bigFileDownloadService.getBigFileBlobLinks(md5);
        String fileName = bigFileDownloadService.getFileName(md5);
        Map<String, Object> ans = new HashMap<>();
        ans.put("links", links);
        ans.put("fileName", fileName);
        return R.okData(ans);
    }

    /**
     * 服务端将大文件合并，将数据整体塞给res的输出流
     * 大小超过10MB的文件不宜使用
     * @param response http response
     * @param md5 文件md5值
     * @param maxBlobSize 分块的最大值
     */
    @GetMapping("/download-big-file")
    @ResponseBody
    public void downloadBigFile(HttpServletResponse response,
                                @RequestParam("md5") String md5,
                                @RequestParam("maxBlobSize") long maxBlobSize) throws IOException {

        response.setContentType("application/octet-stream");

        response.setHeader("Access-Control-Expose-Headers","Content-Disposition");
        response.setHeader("Content-Disposition",
                "attachment; filename=" + md5+bigFileDownloadService.getFileSuffix(md5));
        ServletOutputStream outputStream = response.getOutputStream();
        bigFileDownloadService.mergeBlobToBigFile(md5, maxBlobSize, outputStream);
        outputStream.flush();
    }
}
